<?php declare(strict_types=1);

namespace app\admin\service;

use app\common\helper\ConstBase;
use app\common\model\Article;
use app\common\model\ArticleCategory;
use think\facade\Log;

class ArticleService
{
    /**
     * 列表
     * @return void
     */
    public function getArticleList($pageSize, $startDate, $endDate, $articleId, $keywords, $editor, $categoryId)
    {
        $model = new Article();
        return $model->where(['delete_time'=>0])
            ->field(['id','name','category_id','thumb_url','is_rec','status','sort','add_like','views','create_time','editor'])
            ->where(function ($query) use ($startDate, $endDate, $articleId, $keywords, $editor, $categoryId) {
                if($startDate){
                    $query->whereTime('create_time', '>=', $startDate);
                }
                if($endDate){
                    $query->whereTime('create_time', '<=', $endDate);
                }
                if($articleId){
                    $query->where('id', $articleId);
                }
                if($keywords){
                    $query->where('name|keywords|description|editor', 'like', $keywords .'%');
                }
                if($editor){
                    $query->where('editor', $editor);
                }
                if($categoryId){
                    $query->where('category_id', $categoryId);
                }
            })
            ->order(['sort'=>'desc','id'=>'desc'])
            ->paginate($pageSize)
            ->each(function($item) {
                $item['category_name'] = $this->getCategoryName($item->category_id);
                return $item;
            });
    }

    /**
     * 更新数据
     * @param $data
     * @return void
     */
    public function updateOrInsert($data)
    {
        try {
            $model = new Article();
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $item->save($data);
            } else {
                $model->save($data);
            }
            return json(['code'=>0, 'msg'=>'编辑成功']);
        } catch (\Exception $e) {
            Log::error("edit article error:". $e->getMessage());
            return json(['code'=>1, 'msg'=>'编辑失败，'. $e->getMessage()]);
        }
    }

    /**
     * 文章操作
     * @return void
     */
    public function action($id, $type){
        $model = new Article();
        try {
            $status = $type ? 1:0;
            $model->where('id', $id)->update(['status'=>$status, 'update_time'=>time()]);

            return json(['code'=>0, 'msg'=>'操作成功']);
        } catch (\Exception $e) {
            Log::error("action article {$id} error:". $e->getMessage());

            return json(['code'=>1, 'msg'=>'操作失败，'. $e->getMessage()]);
        }
    }

    /**
     * 删除记录
     * @param $id
     * @return void
     */
    public function delete($id)
    {
        try {
            $ids = !is_array($id) ? [$id]:$id;
            $model = new Article();
            $model::destroy($id);

            return json(['code'=>0, 'msg'=>'删除成功']);
        } catch (\Exception $e) {
            Log::error("delete article " .json_encode($ids). " failed：".$e->getMessage());

            return json(['code'=>1, 'msg'=>'删除失败']);
        }
    }

    /**
     * 查询一条记录
     * @param $id
     * @return Article|array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOne($id)
    {
        $model = new Article();
        return $model->find($id);
    }

    /**
     * 分类列表
     * @return void
     */
    public function getArticleCategoryList($pageSize = MAX_SIZE)
    {
        $model = new ArticleCategory();
        return $model->where(['delete_time'=>0])
            ->field('id,name,type,icon,sort,status,update_time')
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->paginate($pageSize)
            ->each(function ($item) {
                $item['category_article_num'] = $this->getCategoryArticles($item->id);
                $item['type_name'] = $item->type ? ConstBase::ARTICLE_TYPE[$item->type] :'';
                return $item;
            });
    }

    /**
     * 编辑分类
     * @param $data
     * @return \think\response\Json
     */
    public function categoryUpdateOrInsert($data)
    {
        try {
            $model = new ArticleCategory();
            if (isset($data['id'])) {
                $item = $model->find($data['id']);
                $item->save($data);
            } else {
                $model->save($data);
            }
            return json(['code'=>0, 'msg'=>'编辑成功']);
        } catch (\Exception $e) {
            Log::error("edit article category error:". $e->getMessage());
            return json(['code'=>1, 'msg'=>'编辑失败，'. $e->getMessage()]);
        }
    }

    /**
     * 删除分类
     * @param $id
     * @return void
     */
    public function categoryDelete($id)
    {
        $articleItem = (new Article())->where(['status'=>1, 'category_id'=>$id, 'delete_time'=>0])->find();
        if($articleItem){
            return json(['code'=>1, 'msg'=>'请先删除该分类下的文章']);
        }
        try {
            $ids = !is_array($id) ? [$id]:$id;
            $model = new ArticleCategory();
            $model::destroy($id);

            return json(['code'=>0, 'msg'=>'删除成功']);
        } catch (\Exception $e) {
            Log::error("delete article category " .json_encode($ids). " failed：".$e->getMessage());

            return json(['code'=>1, 'msg'=>'删除失败']);
        }
    }

    /**
     * 获取分类
     * @param $categoryId
     * @return void
     */
    public function getCategoryBy($categoryId)
    {
        $model = new ArticleCategory();
        return $model->where('id', $categoryId)->find();
    }

    /**
     * 获取分类名称
     * @param $categoryId
     * @return void
     */
    public function getCategoryName($categoryId)
    {
        $model = new ArticleCategory();
        return $model->where('id', $categoryId)->value('name');
    }

    /**
     * 分类下文章数
     * @param $categoryId
     * @return void
     */
    public function getCategoryArticles($categoryId)
    {
        $model = new Article();
        return $model->where(['category_id'=>$categoryId, 'status'=>1])->count();
    }
}